package com.jjj.springmvc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.alibaba.druid.pool.DruidDataSource;
import com.jjj.springmvc.model.User;

@Repository
public class UserDao {
	private JdbcTemplate jdbcTemplate;
	private JdbcTemplate jdbcTemplate1;
	@Autowired
	public void setDataSource(DruidDataSource dataSource) { 
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	@Autowired
	public void setDataSource1(DruidDataSource dataSource1) { 
		this.jdbcTemplate1 = new JdbcTemplate(dataSource1);
	}
	public List<User> findAllUsers() {
		List<User> list = jdbcTemplate.query("select * from user",new RowMapper<User>() {

			@Override
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				//  获取结果集中的数据
				  User user = new User();
				  user.setId(rs.getString("id"));
				  user.setName(rs.getString("name"));
				  user.setEmail(rs.getString("email"));
				  user.setPassword(rs.getString("password"));
				 return user;
			}
		});
		return list;
	}
	public User findById(String id) {
		String sql = "select * from user where id = ?";
		User user = jdbcTemplate.queryForObject(sql, new String[] {id}, new BeanPropertyRowMapper<>(User.class));
		return user;
	}
	public List<String> findUsersName() {
		String sql = "select user from user ";
		List<String> user = jdbcTemplate1.queryForList(sql, String.class);
		return user;
	}
	public void deleteUserById(String id) {
		String sql = "delete from user where id = ?";
		int count = jdbcTemplate.update(sql, new Object[] {id});
	}
	public void updateUser(User user) {
		String sql = "update user set name=?,password=?,email=? where id=?";
		int count = jdbcTemplate.update(sql, new Object[] {user.getName(),user.getPassword(),user.getEmail(),user.getId()});
	}
	public User findUserByName(String name) {
		String sql = "select * from user where name = ?";
		User user = jdbcTemplate.queryForObject(sql, new String[] {name}, new BeanPropertyRowMapper<>(User.class));
		return user;
	}
	public void deleteAllUser() {
		String sql = "delete from user";
		int count = jdbcTemplate.update(sql);
	}
	public void save(User user) {
		String sql = "insert into user(id,name,email,password,admin,created_at) values(?,?,?,?,?,?)";
		DateTime dt = new DateTime();
		int count = jdbcTemplate.update(sql, new Object[] {user.getId(),user.getName(),user.getEmail(),user.getPassword(),'0',dt.toString("yyyy-MM-dd HH:mm:ss")});
	
	}
}
